package org.example.lysh.tb.router.config;

import org.apache.ibatis.plugin.Interceptor;
import org.example.lysh.tb.router.DBRouterConfig;
import org.example.lysh.tb.router.DBRouterJoinPoint;
import org.example.lysh.tb.router.dynamic.DynamicMybatisPlugin;
import org.example.lysh.tb.router.strategy.IDBRouterStrategy;
import org.example.lysh.tb.router.strategy.impl.DBRouterStrategyHashCode;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author liyishan
 * @date 2023/7/11 18:01
 * @apiNote
 */
@Configuration
public class DataSourceAutoConfig implements EnvironmentAware {
    /**
     * 分表数量
     */
    private int tbCount;
    /**
     * 路由字段
     */
    private String routerKey;


    @Override
    public void setEnvironment(Environment environment) {
        String prefix = "mini-db-router.jdbc.datasource.";
        tbCount = Integer.valueOf(environment.getProperty(prefix + "tbCount"));
        routerKey = environment.getProperty(prefix + "routerKey");
    }


    @Bean
    public Interceptor plugin() {
        return new DynamicMybatisPlugin();
    }


    @Bean
    public DBRouterConfig dbRouterConfig() {
        return new DBRouterConfig(tbCount, routerKey);
    }
    @Bean
    public IDBRouterStrategy dbRouterStrategy(DBRouterConfig dbRouterConfig) {
        return new DBRouterStrategyHashCode(dbRouterConfig);
    }

    @Bean(name = "db-router-point")
    @ConditionalOnMissingBean
    public DBRouterJoinPoint point(DBRouterConfig dbRouterConfig, IDBRouterStrategy dbRouterStrategy) {
        return new DBRouterJoinPoint(dbRouterConfig, dbRouterStrategy);
    }

}
